﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Step4.Unit7.Service.utils;
using System.Linq;
using ZhiJiao.Dal;
using ZhiJiao.Models.Entities;
using ZhiJiao.Models.Entities.Enums;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;

namespace ZhiJiao.Service.Services
{
    public class AccountService : IAccountService
    {
        private readonly BackJson res;
        private readonly UserManager<User> _userManager;
        private readonly ZJDbContext _db;
        private readonly ICurrentUser _currentUser;
         


        public AccountService(BackJson backJson,
                              UserManager<User> userManager,
                              ZJDbContext dbContext,
                              ICurrentUser currentUser)
        {
            res = backJson;
            _userManager = userManager;
            _db = dbContext;
            _currentUser = currentUser;
        }



        #region 获取用户列表
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<BackJson> UserList(AccountFilterDto filter)
        {
            var query = _userManager.Users.Include(u=>u.Instruction).AsQueryable();
            List<User> filterUsers = new List<User>();
            if (filter.UserType == UserType.Plat) // 当前为平台用户
            {
                if (filter.FilterUserType != null)
                {
                    if (filter.FilterUserType == UserType.Plat)  // 查询用户类型  : 平台用户
                    {
                        query = query.Where(u => u.Type == UserType.Plat);
                        if (!string.IsNullOrEmpty(filter.FilterName))
                        {
                            query = query.Where(u => u.Name.Contains(filter.FilterName));
                        }
                    }
                    else // 查询机构用户 
                    {
                        query = query.Where(u => u.Type == UserType.Instruction);
                        if (filter.FilterInsId != null)
                        {
                            query = query.Where(u => u.Instruction != null && u.Instruction.Id == filter.FilterInsId);
                        }
                        if (!string.IsNullOrEmpty(filter.FilterName))
                        {
                            query = query.Where(u => u.Name.Contains(filter.FilterName));
                        }
                    }
                }
                else // 查询所有类型用户
                {
                    if (!string.IsNullOrEmpty(filter.FilterName))
                    {
                        query = query.Where(u=>u.Name.Contains(filter.FilterName));
                    }
                }
            }
            else   // 当前为机构用户
            {
                query = query.Where(u => u.Type == UserType.Instruction);
                if (filter.InsId != null)
                {
                    query = query.Where(u => u.Instruction != null && u.Instruction.Id == filter.InsId);
                }
                else
                {
                    throw new Exception("当前用户为机构用户，但机构ID为空");
                }
                if (!string.IsNullOrEmpty(filter.FilterName))
                {
                    query = query.Where(u => u.Name.Contains(filter.FilterName));
                }
            }
           

            filterUsers = query.OrderBy(u => u.CreateTime).ToList();
            //foreach (var user in users)
            //{
            //    bool inAllRole = true;
            //    foreach (var role in roles)
            //    {
            //        if (!await _userManager.IsInRoleAsync(user, role))
            //        {
            //            inAllRole = false;
            //            break;
            //        }
            //    }
            //    if (inAllRole)
            //    {
            //        filterUsers.Add(user);
            //    }
            //}
            var result = filterUsers.Select(async u => new
            {
                id=u.Id,
                name = u.Name,
                account = u.UserName,
                phone= u.Phone,
                role =await _userManager.GetRolesAsync(u),
                createTime = u.CreateTime.ToString("yyyy-MM-dd hh:mm"),
                type=u.Type,
                flag=u.LockoutEnabled,
                instruction= u.Instruction!=null? u.Instruction.Name :"平台",
                insId=u.Instruction!=null ? u.Instruction.Id :999999
            });
            res.code = 0;
            res.data = result;
            res.msg = "获取用户列表成功";
            return res;
        }
        #endregion


        #region 添加账户
        /// <summary>
        /// 添加账户
        /// </summary>
        public async Task<BackJson> AddSubmit(AddAccountDto account)
        {
            var user = new User();
            user.UserName = account.Account;
            user.NormalizedUserName = account.Account;
            user.Name = account.Name;
            user.LockoutEnabled = !account.Flag;
            user.CreateTime = DateTime.Now;
            user.Type = account.Type;
            user.Phone = account.Phone!;
            if (account.Type == UserType.Instruction)
            {
                user.Instruction = await _db.Instructions.FirstAsync(i => i.Id == account.InsId);
            }
            try
            {
                // 创建用户
                var result = await _userManager.CreateAsync(user, account.Pwd);
                if (result.Succeeded)
                {
                    if (account.Role != null && account.Role.Count > 0)
                    {
                        await _userManager.AddToRolesAsync(user, account.Role);
                        // 将新用户添加到角色
                        res.code = 0;
                        res.msg = "账户添加成功！";
                    }
                    else
                    {
                        res.code = 0;
                        res.msg = "账户添加成功，暂未添加角色";
                    }
                }
                else
                { 
                    List<string> errors = new List<string>();
                    foreach (var err in result.Errors)
                    {
                        errors.Add(err.Description);
                    }
                    res.code = 1;
                    res.msg = string.Join(',', errors);
                }
            }
            catch (Exception e)
            {
                res.code = 1;
                res.msg = e.Message;
            }
            return res;
        }
        #endregion


        #region 删除账户
        /// <summary>
        /// 删除账户
        /// </summary>
        public async Task<BackJson> Delete(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            var result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                res.code = 0;
                res.msg = "用户已删除";
                return res;
            }
            res.code = 1;
            foreach (var err in result.Errors)
            {
                res.msg += (err.Description + "\r\n");
            }
            return res;
        }
        #endregion

        #region 编辑账户
        /// <summary>
        ///  修改用户提交
        /// </summary>
        public async Task<BackJson> EditSubmit(AddAccountDto account)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(account.Id);
                user.UserName = account.Account;
                user.NormalizedUserName = account.Name;
                user.LockoutEnabled = account.Flag;      
                var roles = await _userManager.GetRolesAsync(user);
                await _userManager.RemoveFromRolesAsync(user, roles);// 清除所有角色
                if (account.Role !=null && account.Role.Count>0)
                {
                    await _userManager.AddToRolesAsync(user, account.Role);
                }
                await _userManager.UpdateAsync(user);
                res.code = 0;
                res.msg = "修改用户成功！";
            }
            catch (Exception e)
            {
                res.code = 1;
                res.msg = e.Message;
            }
            return res;
        }
        #endregion

        /// <summary>
        /// 机构选项
        /// </summary>
        public BackJson GetInsOptions()
        {
            var list = _db.Instructions.Where(i => i.IsActive).Select(i => new
            {
                value = i.Id,
                label = i.Name
            });
            res.code = 0;
            res.data = list;
            return res;
        }

        /// <summary>
        /// 获取角色选项
        /// </summary>
        public BackJson GetRoleOptions(RoleType roleType,long? insId)
        {
            // 平台角色
            if (roleType == RoleType.Plat)
            {
                var list = _db.Roles.Where(r => r.Type == roleType).ToList()
                           .Select(r => new
                           {
                               value = r.Name,
                               label = r.Name
                           });
                res.code = 0;
                res.data = list;
            }
            // 机构角色
            else if (roleType == RoleType.Instruction)
            {
                var list = _db.Roles.Where(r => r.Type == roleType && r.Instruction != null && r.Instruction.Id == insId)
                                    .Select(r => new
                                    {
                                        value = r.Name,
                                        label = r.Name
                                    });
                res.code = 0;
                res.data= list;
            }
            return res;
        }
    }
}
